package com.wgo.bpot.domain.common.impl;

import java.util.Date;

import com.wgo.bpot.common.transport.exception.RematoException;
import com.wgo.bpot.domain.common.User;
import com.wgo.bpot.domain.common.UserSession;


public class UserSessionImpl implements UserSession {
	private Date createTime;
	private Date lastActivityTime;
	private User user;
	private String sessionKey;
	private Date expirationTime;
	public static final transient long EXPIRATION_DURATION_MS = 30 * 60 * 1000;
	
    public UserSessionImpl() {
        createTime = new Date();
        lastActivityTime = createTime;
        expirationTime = new Date(createTime.getTime() + EXPIRATION_DURATION_MS);
    }
    public UserSessionImpl(User user) {
        this();
        setUser(user);
    }
	public Date getCreateTime() {
		return createTime;
	}
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}
	public String getSessionKey() {
		return sessionKey;
	}
	public void setSessionKey(String sessionKey) {
		this.sessionKey = sessionKey;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
        if (null == user) {
            throw new RematoException("User cannot be null for user session!");
        }
        this.user = user;
        sessionKey = "" + (user.getUserName() + createTime).hashCode();
	}
	
	public Date getLastActivityTime() {
		return lastActivityTime;
	}
	public void setLastActivityTime(Date lastActivityTime) {
		this.lastActivityTime = lastActivityTime;
	}
	@Override
	public int hashCode() {
		final int PRIME = 31;
		int result = 1;
		result = PRIME * result + ((sessionKey == null) ? 0 : sessionKey.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final UserSessionImpl other = (UserSessionImpl) obj;
		if (sessionKey == null) {
			if (other.sessionKey != null)
				return false;
		} else if (!sessionKey.equals(other.sessionKey))
			return false;
		return true;
	}
	public boolean isExpired() {
		return expirationTime.before(new Date());
	}
	public Date getExpirationTime() {
		return expirationTime;
	}
	public void setExpirationTime(Date expirationTime) {
		this.expirationTime = expirationTime;
	}
	@Override
	public String toString() {
		return "session for " + user.getUserName() + " created at " + createTime.toString();
	}
	
	
}
